package me.khrystal.rxnews.module.video.model;

import com.socks.library.KLog;

import java.util.List;
import java.util.Map;

import me.khrystal.rxnews.bean.NeteastVideoSummary;
import me.khrystal.rxnews.callback.RequestCallback;
import me.khrystal.rxnews.http.HostType;
import me.khrystal.rxnews.http.manager.RetrofitManager;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.functions.Func2;

/**
 * usage:
 * author: kHRYSTAL
 * create time: 16/4/30
 * update time:
 * email: 723526676@qq.com
 */
public class IVideoListInteractorImpl implements IVideoListInteractor<List<NeteastVideoSummary>>{

    @Override
    public Subscription requestVideoList(final RequestCallback<List<NeteastVideoSummary>> callback, final String id, int startPage) {
        return RetrofitManager.getInstance(HostType.NETEASE_NEWS_VIDEO)
                .getVideoListObservable(id,startPage).doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        callback.beforeRequest();
                    }
                }).subscribeOn(AndroidSchedulers.mainThread())
                .flatMap(new Func1<Map<String, List<NeteastVideoSummary>>, Observable<NeteastVideoSummary>>() {
                    @Override
                    public Observable<NeteastVideoSummary> call(Map<String, List<NeteastVideoSummary>> stringListMap) {
                        return Observable.from(stringListMap.get(id));
                    }
                })
                .toSortedList(new Func2<NeteastVideoSummary, NeteastVideoSummary, Integer>() {
                    @Override
                    public Integer call(NeteastVideoSummary neteastVideoSummary, NeteastVideoSummary neteastVideoSummary2) {
                        return neteastVideoSummary2.ptime.compareTo(neteastVideoSummary.ptime);
                    }
                })
                .subscribe(new Subscriber<List<NeteastVideoSummary>>() {
                    @Override
                    public void onCompleted() {
                        callback.requestComplete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e(e + "\n" + e.getLocalizedMessage());
                        callback.requestError(e + "\n" + e.getLocalizedMessage());
                    }

                    @Override
                    public void onNext(List<NeteastVideoSummary> neteastVideoSummaries) {
                        callback.requestSuccess(neteastVideoSummaries);
                    }
                });
    }
}
